﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Windows.Controls.Ribbon;
using Microsoft.Practices.Composite.Presentation.Regions;
using Microsoft.Practices.Composite.Regions;
using WpfRcp.Core.Common;

namespace RibbonControls.Helpers
{
    public class RibbonButtonRegionAdapter : RegionAdapterBase<RibbonButton>
    {
        public RibbonButtonRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory)
            : base(regionBehaviorFactory)
        {
        }

        protected override void Adapt(IRegion region, RibbonButton regionTarget)
        {
            var containingRegion = GroupingViewsCollection.GetRegion(regionTarget);
            if (containingRegion != null)
            {
                containingRegion.Remove(regionTarget);
                string groupName = GroupingViewsCollection.GetGroupName(regionTarget);

                var groups = containingRegion.Views.Where(x => x is RibbonGroup).Cast<RibbonGroup>();
                var group = groups.FirstOrDefault(x => GroupingViewsCollection.GetGroupName(x) == groupName);
                if (group == null)
                {
                    string groupText = GroupingViewsCollection.GetGroupText(regionTarget);
                    group = new RibbonGroup() { Header = groupText };
                    GroupingViewsCollection.SetGroupName(group, groupName);
                    containingRegion.Add(group);
                }
                group.Items.Add(regionTarget);
            }
        }

        protected override IRegion CreateRegion()
        {
            return new SingleActiveRegion();
        }
    }
}
